package com.uploader.service;

import com.uploader.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class FileUploadService {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadService.class);

    @Autowired
    private FileUtils fileUtils;

    // 使用锁来防止并发合并同一文件
    private final Map<String, ReentrantLock> mergeLocks = new HashMap<>();

    /**
     * 检查文件是否已存在或部分上传
     */
    public Map<String, Object> checkFile(String fileHash, String fileName) {
        if (fileHash == null || fileName == null) {
            throw new IllegalArgumentException("文件哈希和文件名不能为空");
        }

        Map<String, Object> result = new HashMap<>();
        boolean exists = fileUtils.checkFileExists(fileName);
        result.put("exists", exists);
        
        if (!exists) {
            // 获取已上传的分片
            List<Integer> uploadedChunks = fileUtils.getUploadedChunks(fileHash);
            result.put("uploadedChunks", uploadedChunks);
            logger.debug("文件未完全上传，已上传分片数: {}", uploadedChunks.size());
        }
        
        return result;
    }

    /**
     * 上传分片
     */
    public void uploadChunk(MultipartFile file, String fileHash, int chunk) throws IOException {
        // 参数验证
        validateUploadParams(file, fileHash, chunk);
        
        logger.debug("接收分片上传请求: fileHash={}, chunk={}, size={} bytes", 
                fileHash, chunk, file.getSize());
        
        try {
            byte[] bytes = file.getBytes();
            fileUtils.saveChunk(bytes, fileHash, chunk);
            logger.debug("分片保存成功: fileHash={}, chunk={}", fileHash, chunk);
        } catch (IOException e) {
            logger.error("分片保存失败: fileHash={}, chunk={}", fileHash, chunk, e);
            // 可以在这里添加失败重试逻辑
            throw new IOException("分片保存失败: " + e.getMessage(), e);
        } catch (Exception e) {
            logger.error("分片处理异常: fileHash={}, chunk={}", fileHash, chunk, e);
            throw new IOException("分片处理异常: " + e.getMessage(), e);
        }
    }

    /**
     * 合并分片
     */
    public void mergeChunks(String fileHash, String fileName, int chunks) throws IOException {
        // 参数验证
        validateMergeParams(fileHash, fileName, chunks);
        
        // 获取或创建合并锁，防止并发合并同一文件
        ReentrantLock lock = getMergeLock(fileHash);
        boolean acquired = false;
        
        try {
            // 尝试获取锁，设置超时时间
            acquired = lock.tryLock(30, TimeUnit.SECONDS);
            if (!acquired) {
                throw new IOException("获取合并锁超时，请稍后重试");
            }
            
            // 再次检查文件是否已存在，防止并发情况下重复合并
            if (fileUtils.checkFileExists(fileName)) {
                logger.warn("文件已存在，跳过合并: {}", fileName);
                return;
            }
            
            logger.info("开始合并文件: fileHash={}, fileName={}, chunks={}", 
                    fileHash, fileName, chunks);
            
            // 执行合并操作
            fileUtils.mergeChunks(fileHash, fileName, chunks);
            
            logger.info("文件合并成功，开始验证MD5值: fileName={}", fileName);
            
            // 计算合并后文件的MD5值并验证
            String mergedFileMd5 = calculateFileMd5(fileUtils.getUploadDir() + File.separator + fileName);
            if (mergedFileMd5 != null && !mergedFileMd5.equalsIgnoreCase(fileHash)) {
                logger.error("文件MD5验证失败: 期望={}, 实际={}, fileName={}", 
                        fileHash, mergedFileMd5, fileName);
                // 删除验证失败的文件
                fileUtils.deleteFile(fileName);
                throw new IOException("文件上传后MD5校验失败，文件可能已损坏");
            }
            
            logger.info("文件MD5验证成功: fileName={}, md5={}", fileName, fileHash);
            
        } catch (IOException e) {
            logger.error("文件合并失败: fileHash={}, fileName={}", fileHash, fileName, e);
            throw e;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("合并操作被中断", e);
        } finally {
            // 释放锁
            if (acquired) {
                lock.unlock();
                // 清理不再需要的锁
                synchronized (mergeLocks) {
                    if (!lock.isLocked()) {
                        mergeLocks.remove(fileHash);
                    }
                }
            }
        }
    }

    /**
     * 验证上传参数
     */
    private void validateUploadParams(MultipartFile file, String fileHash, int chunk) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        if (fileHash == null || fileHash.trim().isEmpty()) {
            throw new IllegalArgumentException("文件哈希不能为空");
        }
        if (chunk < 0) {
            throw new IllegalArgumentException("分片索引不能为负数");
        }
    }

    /**
     * 验证合并参数
     */
    private void validateMergeParams(String fileHash, String fileName, int chunks) {
        if (fileHash == null || fileHash.trim().isEmpty()) {
            throw new IllegalArgumentException("文件哈希不能为空");
        }
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        if (chunks <= 0) {
            throw new IllegalArgumentException("分片数量必须大于0");
        }
        // 验证文件名安全性
        if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
            throw new IllegalArgumentException("文件名包含非法字符");
        }
    }

    /**
     * 获取文件合并锁
     */
    private ReentrantLock getMergeLock(String fileHash) {
        synchronized (mergeLocks) {
            return mergeLocks.computeIfAbsent(fileHash, k -> new ReentrantLock());
        }
    }
    
    /**
     * 计算文件的MD5值
     */
    private String calculateFileMd5(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            logger.error("文件不存在或不是有效文件: {}", filePath);
            return null;
        }
        
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("获取MD5算法实例失败", e);
            return null;
        }
        
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md5.update(buffer, 0, length);
            }
            
            byte[] md5Bytes = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : md5Bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        }
    }
}